package cluster

import (
	"encoding/json"
	"gitee.com/cooge/impush/core"
	"gitee.com/cooge/impush/message"
	"time"
)

var timeLayout = "2006-01-02 15:04:05.999999999"

type clusterUser struct {
	UserId string
	Time   string
}

func SendClusterUsers(userIds []string) []byte {
	clus := make([]*clusterUser, 0)
	for _, k := range userIds {
		ti := core.GetUserAddTime(k)
		if ti != nil {
			ts := ti.Format(timeLayout)
			clu := &clusterUser{k, ts}
			clus = append(clus, clu)
		}
	}
	return sendClusterUsers(clus)
}
func sendClusterUsers(users []*clusterUser) []byte {
	var msg message.Message
	head := make(message.Head)
	head[message.TYPE] = message.CLUSTER
	head[message.ACTION] = message.SEND_CLUSTER_USER
	msg.Heads = head
	ud, err := json.Marshal(users)
	if err == nil {
		msg.Body = ud
	} else {
		msg.Body = []byte{}
	}
	return msg.MessageToByte()
}

func DeleteClusterUsers(userId string, ti *time.Time) []byte {
	ts := ti.Format(timeLayout)
	var clus = []*clusterUser{&clusterUser{userId, ts}}
	return deleteClusterUsers(clus)
}
func deleteClusterUsers(users []*clusterUser) []byte {
	var msg message.Message
	head := make(message.Head)
	head[message.TYPE] = message.CLUSTER
	head[message.ACTION] = message.DELETE_CLUSTER_USER
	msg.Heads = head
	ud, err := json.Marshal(users)
	if err == nil {
		msg.Body = ud
	} else {
		msg.Body = []byte{}
	}
	return msg.MessageToByte()
}
